package com.example.student.web.user;

import cn.hutool.core.lang.UUID;
import com.example.student.web.BaseServlet;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author TonySong
 * @date 2025/8/11 0011
 * @time 10:28
 */
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends BaseServlet {


    private MinioClient builderMinioClient(){
        return MinioClient.builder()
                .endpoint("http://localhost:9000")
                .credentials("root","12345678")
                .build();
    }

    public String minioUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("pic");
        String submittedFileName = part.getSubmittedFileName();
        MinioClient minioClient = builderMinioClient();
        try {
            if(!minioClient.bucketExists(BucketExistsArgs.builder().bucket("test1").build())){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("test1").build());
            }
            String originalFilename = submittedFileName;
            String fileExtension=originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString()+fileExtension;

            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket("test1")
                            .object(objectName)
                            .stream(part.getInputStream(),part.getSize(),-1)
                            .contentType(part.getContentType())
                            .build());

            return objectName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("pic");
        String fileName = UUID.fastUUID().toString(true);
        String name =part.getSubmittedFileName().substring(part.getSubmittedFileName().lastIndexOf(".")+1);
        fileName = fileName+"."+name;
        System.out.println(fileName);
        String realPath = request.getServletContext().getRealPath("/upload/");
        System.out.println("服务器的路径是："+realPath);
        part.write(realPath+ File.separator +fileName);
        return fileName;
    }
}
